package com.jcx.ldzj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcx.ldzj.dao.LoginSystemInfoMapper;
import com.jcx.ldzj.emun.SystemCode;
import com.jcx.ldzj.entity.LoginSystemInfo;
import com.jcx.ldzj.entity.LoginUser;
import com.jcx.ldzj.service.ILoginSystemInfoService;
import com.jcx.ldzj.utile.IpUtils;
import com.jcx.ldzj.utile.RedisUtil;
import com.jcx.ldzj.utile.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ð¡Ìì
 * @since 2021-01-22
 */
@Slf4j
@Service
public class LoginSystemInfoServiceImpl extends ServiceImpl<LoginSystemInfoMapper, LoginSystemInfo> implements ILoginSystemInfoService {

    @Autowired
    private RedisUtil redisclient;
    /**
     * 对登录信息进行记录
     * @param str
     */
    //@Async 不能开异步，因为要获取请求头信息，开了异步就拿不到了
    public boolean setOsAndBrowserInfo(R<String> str){
        String userMap = (String)redisclient.hGet(SystemCode.USER_MAP, str.getData());
        LoginUser loginUser = JSONObject.parseObject(userMap,LoginUser.class);
        log.info("开始存储登录人的信息");
        LoginSystemInfo login=new LoginSystemInfo();
        BeanUtils.copyProperties(loginUser,login);
        login.setId(null);
        //用户信息
        login.setUserId(loginUser.getId());
        login.setUserName(loginUser.getUserName());
        //部门信息
        login.setDepId(loginUser.getDepId());
        login.setDepName(loginUser.getDepName());

        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));  //WINDOWS-CHROME
        //获取浏览器信息
        login.setBrowser(userAgent.getBrowser().getName());
        //获取浏览器版本
        login.setBrowserVersion(userAgent.getBrowserVersion().getVersion());
        //获取浏览器所有语言
        //String languages = ServletUtils.getRequest().getHeader("Accept-Language");
        //获取操作系统
        login.setOperatingSystem(userAgent.getOperatingSystem().getName());
        //获取ip地址
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        login.setHostIp(ip);
        //获取ip所属地
        try{
            login.setLoginLocation(IpUtils.recordIp(ip));
        }catch (Exception e){
            log.error("查询登录人ip出错，错误原因：{}",e);
        }
        //改成在线状态
        login.setLoginStar(str.getCode()==0?'1':'0');
        login.setLoginRemark(str.getMsg());
        return this.save(login);
    }

    @Override
    public List<Map<String, String>> getloginCount() {
        List<Map<String, String>> maps = this.baseMapper.getloginCount();
        return maps;
    }
}
